# -*- coding: utf-8 -*
import os.path
import re
import sys
import logging


class Error(object):

    Ok = 0
    ClassPathInvalid = 1
    OutPathInvalid = 2


class Command:
    """使用正则表达式来进行命令的匹配"""
    helpString = u"""用法 jnitool [选项] [包名]类名
    此程序会调用javap命令，请确保在命令行中可以执行javap命令。此命令类似于javap命令
   -classpath <目录> 指定类文件路径中间不能有空格,不指定则默认是当前目录
   -out <目录> 指定输出路径中间不能有空格,不指定则默认是当前目录
   -help 输出帮助提示
    例子：jnitool -classpath e:\\my_project\\bin\\com\\cn -out e:\\my_project\\src Data
          jnitool -classpath e:\\my_project\\bin com.cn.Data
          jnitool -help
     """

    def __init__(self):
        self.classFalgIndex = -1
        self.outPathFlagIndex = -1
        self.argLength = -1
        self.classPath = os.getcwd()
        self.outPath = os.getcwd()
        self.error = Error.Ok
        self.fileName = ""
        self.filePath = ""

    def parse(self, args):
        """解析参数,解析正确返回True,否则返回False"""
        self.argLength = len(args)
        if not self._regexValidation(args):
            print u"输入的命令格式有错误。请参考:"
            print Command.helpString
            return False
        if self._isHelp(args):
            print Command.helpString
            return True
        else:
            return self._parse(args)

    def _regexValidation(self, args):
        argStr = ""
        if isinstance(args, list):
            argStr = ' '.join(args)
        elif isinstance(args, str):
            argStr = args
        commandReg = '%s%s%s%s' % ("^-help$",
            "|(^-classpath)\s[^-][^\s]+(\s-out\s[^-][^\s]+)?\s[\w\.]+$|",
            "(^-out)\s[^-][^\s]+(\s-classpath\s[^-][^\s]+)?\s[\w\.]+$|",
            "^[\w\.]+$")
        pattern = re.compile(commandReg, re.M)
        m = pattern.match(argStr)
        return m is not None

    def getClassPath(self):
        return self.classPath

    def getOutPath(self):
        return self.outPath

    def getFileName(self):
        return self.fileName

    def getFilePath(self):
        return self.filePath

    def _isValidIndex(self, index):
        if index == -1 or index >= self.argLength-1:
            return False
        return True

    def _parse(self, args):
        try:
            self.classFalgIndex = args.index("-classpath")
        except ValueError:
            self.classFalgIndex = -1
        if self._isValidIndex(self.classFalgIndex):
            path = args[self.classFalgIndex + 1]
            if os.path.isdir(path):
                self.classPath = path
                args.pop(self.classFalgIndex)
                args.pop(self.classFalgIndex)
            else:
                self.error = Error.ClassPathInvalid
        try:
            self.outPathFlagIndex = args.index("-out")
        except ValueError:
            self.outPathFlagIndex = -1
        if self._isValidIndex(self.outPathFlagIndex):
            outPath = args[self.outPathFlagIndex + 1]
            if os.path.isdir(outPath):
                self.outPath = outPath
                args.pop(self.outPathFlagIndex)
                args.pop(self.outPathFlagIndex)
            else:
                self.error = Error.OutPathInvalid

        if self.error == Error.ClassPathInvalid:
            print u"classpath输入的路径不存在"
            return False
        elif self.error == Error.OutPathInvalid:
            print u"out输出的路径不存在"
            return False
        self.fileName = args[0] if len(args) > 0 else ""
        if self.fileName == "":
            print u"请输入文件名"
            return False
        absoultePath = self.classPath + "\\" + self.fileName.replace(".", "\\")\
                        + ".class"
        if not os.path.isfile(absoultePath):
            print absoultePath, u" 文件不存在 "
            return False
        return True

    def _isHelp(self, args):
        try:
            args.index('-help')
            return True
        except ValueError:
            return False
